Chiptune README v2.1
for chiptune full release (v2.1)
2007 Sean Kelly

Contents:
0. If You Have No Patience...
1. Chiptune Overview
2. The Command Line
3. Chiptune's Command-Line Arguments
4. Source File Format
5. Wavelength Table
6. Version Differences
7. Version Info & Known Bugs
8. Contact Info & Purchasing
9. Legal

--== 0. If You Have No Patience... ==--

Follow the steps in section 2, disregard the final paragraph.
Type "./chiptune" (without the quotes) on the command line and press return.
Don't complain to me if something goes wrong.


--== 1. Chiptune Overview ==--

Chiptune is a command-line multichannel sound synthesizer modeled after the capacities of the 8-bit NES' pseudo-Audio Processing Unit (pAPU), MOS Technologies SID chip, and other audio hardware of the era.  It can generate audio files comprised of simple waveforms.  The chiptune demo supports up to 4 channels selected from square wave, triangle wave, and 1-bit random noise, a full version can be requested to support up to any fixed number of channels, plus a few more options.  Output is in the form of an 8-bit (or optionally 16-bit) 44.1khz wav file.


--== 2. The Command Line ==--

Chiptune runs on the command line.  There is no graphical interface.  Command-line applications aren't actually all that scary once you get to know them, however.  For starters, if you're on an OSX machine:
- look in the Applications folder for the Utilities folder
- look in the Utilities folder for an application called Terminal
- double-click Terminal to open the window you'll do everything else in

You should now be looking at a DOS-like prompt (actually it's a variant of BSD UNIX) something like

[computername:~] username:

you are currently operating out of your "home directory" (where the little house icon at the side of a normal Finder window takes you).  If you aren't convinced of this, type "ls" and press return to see a listing of all files in the current directory.

If you don't want to put chiptune and all your input/output files in your home directory, just set up a folder somewhere else to work out of.  Anywhere will do.  When you're ready, 
- type "cd " at the Terminal prompt (do NOT press return yet)
- click and drag the folder where you have chiptune ~into~ the Terminal window.  The window should become outlined until you release the mouse button, at which point the full path to the folder you dragged in should appear right after the "cd "
- now press return.  You are now operating out of the directory containing chiptune.  To verify this, type "ls" and press return again and make sure chiptune is in the list of files displayed.  From here on out this directory will be referred to as the "local directory."

You should now be able to run chiptune by typing "./chiptune" (the "./" is generally required to make sure the command-line shell looks in the local directory (".") for chiptune rather than it's own list of known commands).  If you do so now, you'll generate a file based on the provided sample .ctc files in the provided "tune" directory or generate an error if "tune" is not present in the local directory.  To do more than this, you need to familiarize yourself with chiptune's various arguments.  An argument is anything typed on the command line after an application's name, which the application then uses to determine how it should run.


--== 3. Chiptune's Command-Line Arguments ==--

Chiptune takes arguments to specify where to find input and how to generate output.

"-d SOURCEDIR":
Uses tune data found in local (in the same place as chiptune) directory SOURCEDIR.

"-o OUTFILE":
Specifies that chiptune .wav-format output should be written to a (local) file named OUTFILE rather than the default file "output.wav"

"-16":
Causes chiptune to output a 16-bit wav file.  Each channel will have its 0-255 volume multiplied by 32 (2^5) so that a full 8 (2^3) channels all outputting volume 255 (~2^8) with the same 0 or .999 panning value will very nearly fill the 16-bit maximum volume range (2^16).  The upshot is you will be able to use all 8 tracks at high volume with no clipping or loss of waveform resolution.  The downside is the output file is twice as large as chiptune's standard 8-bit output and music will be very faint if you ~don't~ use most of the available channels at or near full volume.  FULL VERSION ONLY.

"-g GAIN":
Causes output levels to be multiplied by GAIN.  This may increase runtime.  Also note that no clipping detection is done on gain-adjusted output, so too high a GAIN may make resultant audio sound ugly.  FULL VERION ONLY.

"-h":
Causes chiptune to print usage text briefly summarizing the above and then exit immediately.


--== 4. Source File Format ==--

Chiptune is a digital music synthesizer, so you will need some minimum level of music theory and digital theory to understand the source file format and begin writing your own music.

Chiptune source files are simple ASCII text documents containing information specifying each note to be played on a single channel and various tonal qualities to be applied to the waveform used to generate the notes.  If you have the OSX developer package installed, I would reccommend using Simple Text, Project Builder or XCode to write your chiptune files.  Otherwise, use some application which can save in plain ASCII text format (.txt).  Surprisingly enough, TextEdit is not reliably in this category, so stay away from it if you can.

Nearly everything you can specify in a chiptune file is specified through a combination of one letter/symbol (case insensitive) and one number.  Unless otherwise specified, numbers should be decimal integers containing no commas, decimal points, etc.  I have grouped the currently supported specifiers in the following sections:

- Non-Audio -

;
If a semicolon (';') is encountered, any following characters will be ignored until the end of the line.  Use this to add comments to music files.

- Setup -
Specifiers which have default values if left out, but which you'll want to set manually for nearly every file.  You may have multiple specifiers in this category in any given file.  If so, each one will affect all notes between itself and the next specifier of the same type.

L x
Base note length.  All notes specified will play for a multiple of this value.  x is an integer representing the desired duration in 1/44100ths of a second (chiptune outputs 44.1KHz files).

V x
Note volume.  Chiptune uses 8-bit audio output per channel, so x must be an integer between 0 and 255 ((2^8)-1).  Keep in mind that if the sum of the volume across all source channels at a given point in time exceeds 255, clipping will occur.  However, since chiptune outputs in stereo, volume is divided evenly* across left and right output channels.  Thus 2 source channels with v128 will yield net v256, but that 256 is divided across left and right output channels at 128 to each and no clipping should occur.  However, 4 source channels at v128 will result in net v512, meaning both output channels will be at v256, which will be clipped to 255.  If you wish to avoid this clipping at the (sometimes drastic) cost of output volume, use the "-16" command-line parameter to force 16-bit output.

P x
Panning position.  The * from above.  This value affects how the volume of one source channel will be divided across the left and right output channels.  x must be a decimal between .0 and .99999999..., and must lead with the decimal point (no leading 0s).  Default value is .5 if P is not specified.  The left output channel will get volume*(1-x) and the right output channel will get volume*x.

O x
Octave.  x is an integer between 0 and 6 corresponding to one of the generally acepted musical octaves (Google what frequency each is at if you wish) in which you want notes to be played.  Octaves are from C to C, octaves above 6 are not accepted due to inaccuracy of tuning at 44.1khz that high up.

- Notes -
Specifiers that represent individual notes to be played on a given channel.

C x
D x
E x
F x
G x
A x
B x
Notes.  x is the multiple of the value specified with your L base length that you want the note to last.  E.g. if you specified L 22050 (half a second), then A2 would play the note A in the current octave for 1 second.  You can also place any number of '#' or '-' characters between the note character and x.  Each '#' raises the pitch of the note by a half-step, each '-' lowers it by a half-step.  E.g. in the previous example, A#2 would play A-sharp (B-flat) for half a second.

R x
Rest.  Functions the same as a note, but maintains silence on the channel for the duration specified by x.

- Advanced -
Specifiers which affect the sound of notes.  You'll need these to create anything that sounds remotely like good NES music, but some do involve more advanced concepts.

N x/y
N x~y
Volume eNvelope.  x and y are integers, x may be positive or negative.  In the x/y form, volume will jump by x after every y 1/44100th seconds.  Volume envelopes are commonly used to create notes with some level of 'attack' rather than level tones.  In the x~y form, volume will change by x over the first y 1/44100th seconds of the note, return to its original level over the next y 1/44100th seconds, change over the next y, etc. creating a tremolo effect.

S x/y
S x~y
Wavelength Sweep.  Functions like N, only the note wavlength changes by x every y time units.  Keep in mind an increase in wavelength is a decrease in frequency and will lower the note pitch.  A negative value of x will raise the note pitch.  Using the x~y form will create a vibrato effect.

I x
Wave Inflection point.  x must be a decimal between .0 and .99999... with a leading decimal point (no leading 0s).  The default value is .5 if I is not specified.  The first half of the waveform will occur in the first x*100% of the wavelength, the second half will occupy the remainder of the wavelength.  E.g.: On a balanced square wave, output is high for half a wavelength and low for half a wavelength.  With I.3, the waveform will be changed to high for .3 wavelength, low for .7 wavelength.  This is effectively the duty cycle specified on the square wave channels of the pAPU.

*x
Ring modulation.  Multiplies the output of this channel with channel x for subsequent notes.  Only use this one-directionally; e.g. if you modulate channel 1 with channel 3 in channel1.ctc, you do not need to, and indeed should not modulate channel 3 with channel 1 in in channel3.ctc.  While one channel is requesting modulation with another channel, that other channel will automatically cease to directly contribute to output.  To disable ring modulation, use another *y whee y is the current channel; e.g. if channel 1 is currently requesting modulation with channel 3, a '*1' in channel1.ctc will cancel the modulation.  More than 2 channels may be modulated together, but if chaining modulation, the chain should form downwards in channel number; e.g. channel 6 requests modulation with channel 3 in channel6.ctc when channel 3 requests modulation with channel 1 in channel3.ctc resulting in channel 6 being modulated with channel 3 after the modulation of 3 with 1 has been processed.  If x is greater than the highest channel number, this specifier is ignored.  For best results, all but 1 channel in a given ring modulation chain should be at volume 255 since the final output will be at an average level equal to the product of the average levels of all channels in the chain.  FULL VERSION ONLY.

Any number of whitespace characters may exist between specifiers or between a specifier letter and its following number.  All specifiers are supported on all channels.  Exceptions are:
- I does nothing on the noise channel (random noise has no native inflection point)
- noise channel "wavelengths" (the period for which a given random bit is held on output) are autimatically decreased shifting frequency up by 3 octaves to allow access to the percussive ranges usually used on the square wave channel.

All source files used in a particular tune should represent the same amount of time (that time may still be subdivided into notes however you wish).  If source files represent unequal lengths of output, processing will stop at the end of the shortest file.


Data files must be named "channelX.ctc" where X is an integer counting from 0, and should be placed in a single directory.  E.g. a 4-channel tune would have files channel0.ctc, channel1.ctc, channel2.ctc and channel3.ctc.
One additional file named "channels.txt" is also required in the directory.  channels.txt should contain a series of integers separated by whitespace: the number of channels in the tune, and the wave types of each channel in order.  Wave types are:
  0: square wave
  1: triangle wave
  2: random noise
  3: sine wave (FULL VERSION ONLY)
  4: 16-level stepped pseudo-triangle wave (FULL VERSION ONLY)
The contents of channels.txt for a 4-channel NES pAPU-style tune might look like
     4
     0 0 1 2
4 channels, named appropriately, consisting of 2 square waves, 1 triangle and 1 noise.

--== 5. Wavelength Table ==--

For those of you who care, this is the array used by chiptune to look up wavelengths.  It starts at octave 0 and goes through octave 6.  It could be useful if you're looking to match particular pitches with wavelength sweep effects.

const unsigned int pitcharray[]=
	{
	//A 27.5
	2697,2546,2403,2267,2140,2020,1907,1800,1699,1604,1513,1429,
	//A 55
	1349,1273,1201,1134,1070,1010,954,900,850,802,757,714,
	//A 110
	674,636,601,567,535,505,477,450,425,401,378,357,
	//A 220
	337,318,300,283,268,253,238,225,212,200,189,179,
	//A 440
	169,159,150,142,134,126,119,113,106,100,95,89,
	//A 880
	84,80,75,71,67,63,60,56,53,50,47,45,
	//A 1760
	42,40,38,35,33,32,30,28,27,25,24,22
	};


--== 6. Version Differences ==--

The chiptune demo supports up to 4 manually specified channels selectable from square wave, triangle wave, and 1-bit noise.

The full version, available for as little as $1 (see below) features
- an arbitrary number of fully-specifiable channels
- sine wave and pseudo-triangle channel support
- future plans for more channel types, including saw wave and perhaps sampled PCM or delta-modulation
- optimized compilation (increased speed)
- optional 16-bit output file support



--== 7. Version Info & Known Bugs ==--

*	0.7 basic functionality present, first trial release
*	0.8 adds basic command-line parameter handling (default mode or local directory)
*	0.9 adds full command-line parameter handling for variable number of channels
*	0.91 adds basic menu-driven interface, fixes first-note-only bug on newer compilers
*	1.0 adds
*		sine wave
*		explicit inlining (~10% speedup)
*		4 channels (i.e. unlocks all 8)
*		channel function data passing revision (notespec struct- 1 pointer rather than 13 values)
*		first public release
*	1.1 adds 
*		saw wave masking function (* specifier)
*		16-bit adjusted output (-16 argument)
*	1.11 fixes saw-mask to adjust to centerline (countering volume loss), refines 16-bit output centering
*		added ';' line-comment char to file format
*	1.12 "fixes" bug triggered by negative sweep values 
*		Fix may cause slight popping of new notes on tone channels, and long-term (overflow/underflow)
*		behavior of swept notes has not been actively reconsidered
*   2.0 is a complete overhaul of the code, breaking it down into an independent audio data generation 
*       class working from a more fixed file hierarchy and a new frontend.
*   2.1 improves code quality in multiple places, fixes a spin-lock bug resulting from files with trailing
*		comments and no newline, adds true ring modulation.

I have not abusively tested the program, so it is very possible that you could break it by intentionally throwing large amounts of irregular or invalid syntax/specifiers/arguments/etc. at it.  In this case, its poor performance is YOUR OWN BLOODY FAULT.  Report it if you wish, but I won't be helping you explicitly with the problem.  If you pin down any bugs that show up while attempting to comply with regular file/argument formatting and volume balance, e-mail me.


--== 8. Contact Info and Purchasing ==--

If you want to e-mail me, the current address is redmage.spkelly@gmail.com.

Chiptune 2.x is shareware.  The DEMO version may be used free of charge according to section 9 below.
A full version of chiptune may be acquired as described below:
 SINGLE: A full version of the latest build of chiptune is priced at $1 per channel.  The basic 4 channels, but with FULL VERSION feature support will thus run you only $4.  More channels per tune will cost you more.  Sadly, while I can set the maximum number of channels arbitrarily high, it does need to be set at compile time for a couple parts of the code to work happily, so there is no 'unlimited channels' version pricing currently available.
 SUBSCRIPTION: 'Subscription' to chiptune updates may be purchased for an additional $5.  So long as I have valid contact information for you, I will send you updated updated versions of command-line chiptune 2.x, at your specified number of channels, as they are completed.  At my discretion, I may continue sending you updates of ~any~ future versions of chiptune or increase your channel limit as changes in the code dictate.
 UPGRADE 2.x: If you have an existing full version of chiptune 2.x and are in my records as having such, you may request an increase in your number of supported channels for $1 per channel added plus a $2 processing fee.  This pricing applies for single and subscription customers, and the upgraded application will be of the latest chiptune version regardless (yes, this means single customers can request a 0 channel increase for $2 to obtain the latest build).
 UPGRADE 1.x: If you have an existing full version of chiptune 1.x and are in my records as having such, you may ONCE ONLY deduct $1 from a purchase or upgrade of chiptune 2.x.  If you have previously paid for the chiptune 1.x continued update arrangement, you may instead deduct $5 ONE TIME ONLY from a purchase or upgrade of chiptune 2.x so long as the net cost you pay after the deduction is $0 or greater.
 ENGINE: As of version 2.x, the chiptune audio core is available as a stand-alone library for use in any C++ software project.  As a stand-alone engine, it can parse chiptune files as described above and deliver arbitrarily sized chunks of raw PCM audio data suitable for most streaming or continuous-play audio applications.  For details on chiptune as an audio engine, and to discuss pricing and limitations of use of the code, contact me.  Base pricing will be higher than that of the application chiptune, may be proportional to the number of channels you require, and may include an additional charge proportional to the price of your software and units sold.

If you want to get the full version of chiptune, e-mail me first to make sure the address is still working and to make sure there is a full version to get.  I will respond with whatever methods of payment I have set up and e-mail you the full version as soon as I receive your donation.  IF I HAVE NOT HEARD THAT YOU ARE GOING TO SEND MONEY BEFORE YOU ACTUALLY SEND IT, YOUR SENDING MONEY DOES NOT REPRESENT A BINDING AGREEMENT WITH ME TO SEND YOU THE SOFTWARE.  I don't want to be mean or steal your money, but I check my paper mail and paypal so infrequently that if I don't know money is coming, I may very well not notice that I have it for months.

--== 9. Legal Jargon ==--

I hate to be an ass here, but all the same, I want to keep myself covered in the event anyone tries to pull a fast one.  So here's the beef:

 The portions of the source code of chiptune not contained in stock C/C++ libraries are copyright and the sole property of Sean Kelly, henceforth referred to as "the author".  Redistribution or profitable use of said source code without his consent is strictly prohibited.
 The compiled binaries of chiptune, for any platform, are yours to keep and use individually on as many machines owned by you as you wish, and up to one (1) machine not owned by but regularly used by you which you would otherwise have permission to install chiptune on.  Chiptune demo (v0.91) is freeware and may be distributed free by you to anyone you wish provided all chiptune executable content, samples and documentation originally obtained by you have not been modified from their original form and are included in the package you distribute.  Chiptune 1.x and higher are only available from the author and any party to which  he explicitly grants the right to distribute copies and manage donations/payments.  Distribution of chiptune 1.x and higher without the permission of the author, and distribution of any version of chiptune for any kind of payment save by the author is strictly prohibited.
 You may not in any way extend or reverse engineer any version of chiptune for other than personal use.  Distribution of any work derived from chiptune without express permission from the author is prohibited.
 No audio output generated by or other media derived from chiptune may ever be exchanged for payment in any form.  If you wish to be excepted from this rule, contact the author to receive per-tune consent and, if relevent, discuss royalties.  Permission granted to distribute any media generated by chiptune is contingent on and does in no way supercede or alter your rights to any existing media you use chiptune to recreate, remix, modify, etc.
 This document and any other documentation included with chiptune may not be modified by any party apart from the author, and may be revised by the author at any time without notification.  The most recent version of the documentation in the author's posession supercedes any prior versions and shall be used in the resolution of any disputes regarding any version of chiptune.
 RECEIPT OF THIS DOCUMENT AND USE OF THE CHIPTUNE SOFTWARE CONSTITUTE AN AGREEMENT BY THE RECIPIENT/USER TO ABIDE BY THE CONTENTS OF THIS DOCUMENT.
 Just use common sense.  Please.